import { IHttpResponse } from '@ibiz-template/core';
import { ListController, MDCtrlLoadParams } from '@ibiz-template/runtime';

export class EXTVIEW1ListController extends ListController {
  /**
   * 部件加载数据行为
   *
   * @date 2022-08-19 14:08:50
   */
  async load(args: MDCtrlLoadParams = {}): Promise<IData[]> {
    if (this.state.isSimple) {
      return [];
    }
    await this.startLoading();
    try {
      // *初始加载需要重置分页
      const isInitialLoad = args.isInitialLoad === true;
      const isLoadMore = args.isLoadMore === true;
      if (isInitialLoad) {
        this.state.curPage = 1;
      } else if (isLoadMore) {
        this.state.curPage += 1;
      }

      // *查询参数处理
      const { context } = this.handlerAbilityParams(args);
      const params = await this.getFetchParams(args?.viewParam);
      const keyPSDEField = this.dataEntity.name
        ? this.dataEntity.name.toLowerCase()
        : 'data_resource';
      const keyField = this.controlParams.KEYFIELD
        ? this.controlParams.KEYFIELD
        : 'id';
      const config = {
        configUrl: this.controlParams.configurl,
        fetchUrl: this.controlParams.fetchurl,
        createUrl: this.controlParams.createurl,
        updateUrl: this.controlParams.updateurl,
        removeUrl: this.controlParams.removeurl,
        saveBatchUrl: this.controlParams.savebatchurl,
        removeBatchUrl: this.controlParams.removebatchurl,
      };
      const url = this.getTargetUrl(
        config.fetchUrl,
        keyPSDEField,
        keyField,
        params,
      );
      const res: IHttpResponse = await ibiz.net.post(url, params);
      // 更新分页数据总条数
      if (typeof res.total === 'number') {
        this.state.total = res.total;
      }
      const data = res.data as IData[];
      if (isLoadMore) {
        this.state.items.push(...data);
      } else {
        this.state.items = data;
      }

      await this.afterLoad(args, data);

      this.state.isLoaded = true;
      await this._evt.emit('onLoadSuccess', {
        isInitialLoad,
      });
    } catch (error) {
      await this._evt.emit('onLoadError', undefined);
      this.actionNotification('FETCHERROR', {
        error: error as Error,
      });
      throw error;
    } finally {
      await this.endLoading();
    }

    this.actionNotification('FETCHSUCCESS');
    return this.state.items;
  }

  /**
   * 计算目标路径
   * @param url
   * @param data
   * @returns
   */
  public getTargetUrl(
    url: string,
    keyPSDEField: string,
    keyField: string,
    data: IData,
  ) {
    let targetUrl = '';
    const metadataid = data[keyPSDEField];
    targetUrl = url.replaceAll('{metadataid}', metadataid);
    if (data) {
      targetUrl = targetUrl.replaceAll('{id}', data[keyField]);
    }
    return targetUrl;
  }
}
